﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace HCLSMod.NetSocket
{
    public class TCPClientSocket : ZLErrorRecord
    {
        #region 成员

        public Socket fClientSocket { get; set; }
        private Thread fClientThd { get; set; }

        private bool fisConnected = false;
        protected IPEndPoint fDestIPEnd { get; set; }

        public event SocketRecDataCallBack OnReceive;
        public event SocketEventCallBack OnServerClosed;
        public event SystemEventLog OnEventLog;
                
        /// <summary>
        /// 服务器地址
        /// </summary>
        public string DestAddress { get { return fDestIPEnd.Address.ToString(); } }

        /// <summary>
        /// 服务器监听端口
        /// </summary>
        public int DestPort { get { return fDestIPEnd.Port; } }
        /// <summary>
        /// 目标服务器地址及IP信息
        /// </summary>
        public IPEndPoint DestIPEndPoint
        {
            get { return fDestIPEnd; }
            set { fDestIPEnd = value; }
        }

        /// <summary>
        /// 是否与服务器处于连接状态
        /// </summary>
        public bool IsConnected { get { return fisConnected; } }

        public TCPClientSocket()
        {
        }

        public TCPClientSocket(IPEndPoint HostEndPointInfoX)
        {
            DestIPEndPoint = HostEndPointInfoX;
        }
        #endregion

        /// <summary>
        /// 连接服务器
        /// </summary>
        /// <returns>返回是否成功连接到目标地址</returns>
        public bool Connect()
        {
            try
            {
                if (DestIPEndPoint != null)
                {

                    fClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    fClientSocket.Connect(DestIPEndPoint);
                    fisConnected = true;

                    // 已经有接收数据处理事件，则启动接收线程
                    if (OnReceive != null)
                    {
                        fClientThd = new Thread(new ThreadStart(ReceiveData));
                        fClientThd.Name = "接收数据";
                        fClientThd.Start();
                    }
                }
                return fisConnected;
            }
            catch (Exception ex)
            {
                PutErrorEvent(ex);
                if (OnEventLog != null)
                {
                    OnEventLog(this, EventLogEntryType.Error, ex.Message);
                }
                return false;
            }
        }
        /// <summary>
        /// 连接服务器
        /// </summary>
        /// <param name="hostAddress">服务器地址</param>
        /// <param name="port">服务器监听端口</param>
        public bool Connect(IPEndPoint HostEndPointInfoX)
        {
            DestIPEndPoint = HostEndPointInfoX;
            return Connect();
        }
        /// <summary>
        /// 关闭与服务器的连接
        /// </summary>
        public virtual void Close()
        {
            fisConnected = false;
            try
            {
                if (fClientThd != null)
                {
                    //fClientThd.Abort();                    
                    fClientThd = null;
                }
                Thread.Sleep(2);
                if (fClientSocket != null)
                {
                    if (fClientSocket.Connected)
                        fClientSocket.Shutdown(SocketShutdown.Both);
                    fClientSocket.Close();
                    fClientSocket = null;
                }
            }
            catch (Exception ex)
            {
                PutErrorEvent(ex);
                if (OnEventLog != null)
                {
                    OnEventLog(this, EventLogEntryType.Error, ex.Message);
                }
            }
        }
        /// <summary>
        /// 接受数据线程
        /// </summary>
        private void ReceiveData()
        {
            byte[] buff = new byte[1024];
            while (fisConnected)
            {
                try
                {
                    int fRecCount = 0;

                    if (fClientSocket.Connected)
                    {
                        // 检查Socket中接收缓冲区中是否收到数据，及数据数量
                        // 此方式将产生阻塞，不会占用CPU运算
                        // 该方式将会占用大量的CPU运算，建议增加Sleep(1)
                        fRecCount = fClientSocket.Available;
                        //fRecCount= fClientSocket.Receive(buff, SocketFlags.Peek);
                        if (fRecCount > 0)
                        {
                            byte[] fRecBuf = new byte[fRecCount];
                            // 接收数据，并清除接收缓冲区
                            fClientSocket.Receive(fRecBuf, SocketFlags.None);
                            SetRxRecord(new ZLByteDataRecord(fRecBuf));
                            OnReceive?.Invoke(this, fClientSocket, ref fRecBuf);
                        }
                    }
                    Thread.Sleep(1);
                }
                catch (Exception ex)
                {
                    PutErrorEvent(ex);
                    if (OnEventLog != null)
                    {
                        OnEventLog(this, EventLogEntryType.Error, ex.Message);
                    }
                }
            }
        }
        /// <summary>
        /// 发送数据
        /// </summary>
        /// <param name="fSendStr">数据</param>
        public int Send(string fSendStr)
        {
            if (fisConnected)
            {

                SetTxRecord(new ZLByteDataRecord(Encoding.UTF8.GetBytes(fSendStr)));
                return fClientSocket.Send(Encoding.UTF8.GetBytes(fSendStr));
            }
            return 0;
        }

        public int Send(byte[] fSendDatas)
        {
            if (fClientSocket.Connected && (fClientSocket != null) && (fClientSocket.Connected))
            {
                SetTxRecord(new ZLByteDataRecord(fSendDatas));
                return fClientSocket.Send(fSendDatas);
            }
            return 0;
        }
    }
}
